package com.itrui.encrypted_transmission;

import java.io.*;
import java.util.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class CodeUtils {
    static private Base64.Decoder decoder = Base64.getDecoder();
    static private Base64.Encoder encoder = Base64.getEncoder();

    //字符数组编码文件
    public static String encodeFile(byte[] bytes)
    {
        return encoder.encodeToString(bytes);
    }
    //流编码文件
    public static String encodeFile(InputStream in)
    {
        String s = null;
        try {
            System.out.println("读取文件...");
            BufferedImage bi = ImageIO.read(in);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "png", baos);
            byte[] bytes = baos.toByteArray();
            System.out.println("编码...");
            s = encoder.encodeToString(bytes);
            baos.close();
        }
        catch(IOException e) {

        }
        return s;
    }
    //文件路径编码文件
    public static String encodeFile(String path)
    {
        String s = null;
        File file = new File(path);
        try {
            BufferedImage bi = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "png", baos);         //把文件的二进制编码传入字节流
            byte[] bytes = baos.toByteArray();
            s = encoder.encodeToString(bytes);      //编码成字符串
            //System.out.println(s);
            baos.close();
        }
        catch(IOException e) {
            System.out.println("找不到文件!!!");
        }
        return s;
    }
    //译码文件
    public static byte[] decodeFile(String s)
    {
       //return  decoder.decode(s);
        return Base64.getMimeDecoder().decode(s);
    }

    //写出文件文件，写入path路径下
    public static void loadFile(String imag_bytes, String path)
    {
        try {
            //byte[] bytes = decoder.decode(imag_bytes);       //把字符串译码为二进制
            byte[] bytes = Base64.getMimeDecoder().decode(imag_bytes);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            BufferedImage bi = ImageIO.read(bais);

            File w2 = new File(path);
            ImageIO.write(bi, "png", w2);           //写文件

            bais.close();
        }
        catch(IOException e) {
            System.out.println("写入文件文件失败!!!");
        }
    }
}
